﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.Common;
using Aliyeye.Car.Net.UI.PrintExport;
using Aliyeye.Car.Net.UI.SystemHelp;

namespace Aliyeye.Car.Net.UI.OrderModel
{
    public partial class SettlementShort : BaseForm
    {
        public SettlementShort()
        {
            InitializeComponent();
        }

        CarSvc.SoapHeaderClass sopaHeaderCAR = new Aliyeye.Car.Net.UI.CarSvc.SoapHeaderClass();
        ReserveSvc.SoapHeaderClass sopaHeaderReserveSvc = new Aliyeye.Car.Net.UI.ReserveSvc.SoapHeaderClass();
        CarSvc.Car modelCar = new Aliyeye.Car.Net.UI.CarSvc.Car();

        ReserveSvc.Reserve modelReserve = new Aliyeye.Car.Net.UI.ReserveSvc.Reserve();
        Model.Customer customerInfo = new Model.Customer();

        private int carId = 0;
        private int reserveID = 0;
        private bool isSave = false;
        private string payType = "";

        public SettlementShort(int intCarId, int intResID)
        {
            InitializeComponent();

            this.carId = intCarId;
            this.reserveID = intResID;

        }

        private void Settlement_Load(object sender, EventArgs e)
        {
            lblNowDate1.Text = lblNowDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            endTime = DateTime.Now;

            BindInfo();

        }


        private void BindInfo()
        {

            if (carId > 0)
            {
                overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;

                ServiceManipulator.SafeAsyncExecution<CarSvc.CarServiceSoapClient>(
                   proxy => proxy.GetModel(sopaHeaderCAR, carId),
                   result =>
                   {
                       if (result.Error == null)
                       {
                           modelCar = (CarSvc.Car)result.Result;
                           if (modelCar != null)
                           {
                               //车辆信息
                               carCode = lblCarCode.Text = modelCar.Code.ToString();
                               lblDayKm.Text = modelCar.DayLimitKM.ToString();
                               lblOvertimePrie.Text = modelCar.OvertimePrie.ToString();
                               lblTimeoutPrie.Text = modelCar.TimeoutPrie.ToString();
                               //lblCarRent.Text=
                               //lblCarMax.Text = modelCar.Max.ToString();
                               lblCarBrand.Text = modelCar.Brand;
                               lblCartype.Text = modelCar.Cartype;

                               //lblOvertimeAmount.Text = (0 - Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                               //lblSuperDriverAmount.Text = (0 - Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();
                               lblOvertimeAmount.Text = (Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                               lblSuperDriverAmount.Text = (Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();
                           }
                       }
                       else
                       {
                           PageCommon.Error(result.Error.Message);
                           overlay.FadeOut(); Cursor.Current = Cursors.Default;
                       }
                   },
                   this
               );
            }

            if (reserveID > 0)
            {
                ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
                    proxy => proxy.GetModel(sopaHeaderReserveSvc, reserveID),
                    result =>
                    {
                        if (result.Error == null)
                        {
                            modelReserve = (ReserveSvc.Reserve)result.Result;

                            //订单起始公里数
                            lblCarMax.Text = modelReserve.CurrentMax.ToString();

                            //超时计价
                            if (modelReserve.PriceType2.Trim() == "包车三小时租金" || modelReserve.PriceType2.Trim() == "包车八小时租金")
                            {
                                lblTimeoutPrie.Text = modelReserve.OutdatedFee.ToString();
                            }

                            //客户信息
                            lblCode.Text = modelReserve.Code;
                            lblCustomerCode.Text = customerInfo.Code = modelReserve.CustomerCode;
                            lblCustomerName.Text = customerInfo.Name = modelReserve.CustomerName;
                            lblCustomerComp.Text = customerInfo.ComName = modelReserve.ComName;
                            lblCustomerType.Text = modelReserve.CustomerType.Trim() == "1" ? "个人用户" : "企业用户";

                            payType = modelReserve.PayType.Trim();

                            lblCarRent.Text = modelReserve.ZPrice + "/" + modelReserve.DeadLineType;

                            lblBookingDate.Text = modelReserve.BookTime.ToString("yyyy-MM-dd HH:mm:ss");
                            lblEndBookDate1.Text = lblEndBookDate.Text = modelReserve.EndBooktime.ToString("yyyy-MM-dd HH:mm:ss");
                            beginTime = modelReserve.BookTime;

                            //超时计算
                            Int64 timeout = Convert.ToInt64(DateTime.Now.Subtract(modelReserve.EndBooktime).TotalHours);
                            if (timeout > 0)
                                lblTimeOut.Text = timeout.ToString();
                            else
                                lblTimeOut.Text = "0";

                            string reserveType = "";
                            // 1: 长租自驾2:短租自驾 3: 长租带驾4:短租带驾
                            switch (modelReserve.Type)
                            {
                                case 1:
                                    reserveType = "长租自驾";
                                    break;
                                case 2:
                                    reserveType = "短租自驾";
                                    break;
                                case 3:
                                    reserveType = "长租带驾";
                                    break;
                                case 4:
                                    reserveType = "短租带驾";
                                    break;
                            }
                            lblReserveType.Text = reserveType;

                            //lblDeposit1.Text = lblDeposit.Text = "-" + modelReserve.Deposit.ToString();
                            lblDeposit1.Text = lblDeposit.Text = modelReserve.Deposit.ToString();
                            //结算信息
                            //lblRentReceivable.Text = (0 - modelReserve.ZPrice * modelReserve.DeadLine).ToString();
                            //lblReceivedAmount.Text = "+" + (modelReserve.Rent + modelReserve.Deposit).ToString();
                            //lblOvertimeAmount.Text = (0 - Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                            //lblSuperDriverAmount.Text = (0 - Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();
                            lblRentReceivable.Text = (modelReserve.ZPrice * modelReserve.DeadLine).ToString();
                            lblReceivedAmount.Text = (modelReserve.Rent + modelReserve.Deposit).ToString();
                            lblOvertimeAmount.Text = (Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();
                            lblSuperDriverAmount.Text = (Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();

                            //lblDeposit.Text = "+" + modelReserve.Deposit.ToString();

                            txtMarks.Text = modelReserve.Marks;

                            //Cmbpaytype.Text = modelReserve.PayType;

                            //lblUser.Text = modelReserve.UserTrueName;
                            customerInfo.Tel = modelReserve.Tel;

                            customerInfo.Addr = modelReserve.CustomerAddr;
                            customerInfo.CodeCar = modelReserve.CustomerCodeCar;
                            customerInfo.DriCard = modelReserve.CustomerDriCard;
                            customerInfo.Phone = modelReserve.CustomerPhone;

                            GetRepairAndIllegalSumPrice();
                            overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        }
                        else
                        {
                            PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        }
                    },
                    this
                );
            }
        }
        string carCode = string.Empty;
        DateTime beginTime = new DateTime(1900, 1, 1);
        DateTime endTime = new DateTime(1900, 1, 1);

        private void GetRepairAndIllegalSumPrice()
        {
            RepairSvc.SoapHeaderClass sopaHeaderRepair = new Aliyeye.Car.Net.UI.RepairSvc.SoapHeaderClass();
            IllegalSvc.SoapHeaderClass sopaHeaderIllegal = new Aliyeye.Car.Net.UI.IllegalSvc.SoapHeaderClass();
            //overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;

            RepairSvc.RepairServiceSoapClient repairClient = new Aliyeye.Car.Net.UI.RepairSvc.RepairServiceSoapClient();
            lblRepairDamage1.Text = lblRepairDamage.Text = repairClient.GetSumPriceByCarCode(sopaHeaderRepair, carCode, beginTime, endTime).ToString();

            IllegalSvc.IllegalServiceSoapClient IllegalClient = new Aliyeye.Car.Net.UI.IllegalSvc.IllegalServiceSoapClient();
            lblTotalFines1.Text = lblTotalFines.Text = IllegalClient.GetSumPriceByCarCode(sopaHeaderIllegal, carCode, beginTime, endTime).ToString();

            GetTotalAmount();
        }

        private bool IsNumberMoney(System.Windows.Forms.TextBox t, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '.' || e.KeyChar == 8 || e.KeyChar == 13))
            {
                return true;
            }
            else
            {
                PageCommon.Alert("只能输入数字！");
                e.Handled = true;
                return false;
            }
        }

        private void txtCurrentKM_KeyPress(object sender, KeyPressEventArgs e)
        {
            IsNumberMoney(txtCurrentKM, e);
        }

        private void txtCurrentKM_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCurrentKM.Text))
                return;
            Int64 LimitKM = 0;
            switch (modelReserve.DeadLineType.Trim())
            {
                case "年":
                    LimitKM = modelCar.YearLimitKM;
                    break;
                case "月":
                    LimitKM = modelCar.MonthLimitKM;
                    break;
                case "日":
                    LimitKM = modelCar.DayLimitKM;
                    break;
                case "次":
                    LimitKM = modelCar.DayLimitKM;
                    break;
            }

            Int64 sumLimitKM = LimitKM * modelReserve.DeadLine;

            Int64 km = Convert.ToInt64(txtCurrentKM.Text) - sumLimitKM - Convert.ToInt64(lblCarMax.Text);
            if (km > 0)
                lblSuperDriver.Text = km.ToString();
            else
                lblSuperDriver.Text = "0";

            //lblSuperDriverAmount.Text = (0 - Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();
            lblSuperDriverAmount.Text = (Convert.ToDecimal(lblOvertimePrie.Text) * Convert.ToDecimal(lblSuperDriver.Text)).ToString();

            GetTotalAmount();
        }

        private void GetTotalAmount()
        {
            //decimal sum = Convert.ToDecimal(lblRentReceivable.Text) +
            //    Convert.ToDecimal(lblReceivedAmount.Text) +
            //    Convert.ToDecimal(lblOvertimeAmount.Text) +
            //    Convert.ToDecimal(lblSuperDriverAmount.Text) +
            //    Convert.ToDecimal(lblTotalFines.Text) +
            //    Convert.ToDecimal(lblDeposit.Text) -
            //    Convert.ToDecimal(lblOtherAmount.Text) +
            //    Convert.ToDecimal(lblRepairDamage.Text);

            //if (sum > 0)
            //    lblTotalAmount.Text = "+" + sum.ToString();
            //else
            //    lblTotalAmount.Text = sum.ToString();

            decimal sum = Convert.ToDecimal(lblReceivedAmount.Text) -
                Convert.ToDecimal(lblRentReceivable.Text) -
                Convert.ToDecimal(lblOvertimeAmount.Text) -
                Convert.ToDecimal(lblSuperDriverAmount.Text) -
                Convert.ToDecimal(lblTotalFines.Text) -
                //Convert.ToDecimal(lblDeposit.Text) +
                Convert.ToDecimal(lblOtherAmount.Text) -
                Convert.ToDecimal(lblRepairDamage.Text);

            lblTotalAmount.Text = sum.ToString();

            if (sum > 0)
                lblTotalAmount.ForeColor = Color.Blue;
            else
                lblTotalAmount.ForeColor = Color.Red;
        }

        //结算
        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveInfo();
        }

        private void SaveInfo()
        {
            if (string.IsNullOrEmpty(txtCurrentKM.Text))
            {
                PageCommon.Alert("请输入当前公里数！");
                return;
            }

            if (Convert.ToDecimal(txtCurrentKM.Text) < Convert.ToDecimal(lblCarMax.Text))
            {
                PageCommon.Alert("当前公里必须大于出车里数，请重新输入当前公里数！");
                return;
            }

            //餐费住宿费
            decimal MealsAccommodation = Convert.ToDecimal(lblOtherAmount.Text);
            //违章保留
            decimal IllegalRetention = 0;

            ReserveSvc.SoapHeaderClass sopaHeaderReserveSvc = new Aliyeye.Car.Net.UI.ReserveSvc.SoapHeaderClass();
            //ReserveSvc.Reserve model = new Aliyeye.Car.Net.UI.ReserveSvc.Reserve();
            modelReserve.MealsAccommodation = MealsAccommodation;
            modelReserve.IllegalRetention = IllegalRetention;
            modelReserve.Marks = txtMarks.Text;
            modelReserve.RentReceivable = Convert.ToDecimal(lblRentReceivable.Text);
            modelReserve.ReceivedAmount = Convert.ToDecimal(lblReceivedAmount.Text) - Convert.ToDecimal(lblTotalAmount.Text);
            modelReserve.OvertimeAmount = Convert.ToDecimal(lblOvertimeAmount.Text);
            modelReserve.SuperDriverAmount = Convert.ToDecimal(lblSuperDriverAmount.Text);
            modelReserve.TotalFines = Convert.ToDecimal(lblTotalFines.Text);
            modelReserve.DepositReturn = Convert.ToDecimal(lblDeposit.Text);
            modelReserve.RepairDamage = Convert.ToDecimal(lblRepairDamage.Text);
            modelReserve.TotalAmount = 0;

            modelReserve.IsReturnIllegal = true;
            modelReserve.IsCompletedCheckout = true;

            modelReserve.SettlementDate = DateTime.Now;
            modelReserve.SettlementUserID = Login.LogUserId;
            decimal InputBillingAmount = -Convert.ToDecimal(lblTotalAmount.Text);

            long points = 0;
            //获取会员积分
            if (payType.Trim() != "会员积分")
            {
                ArchivesSvc.SoapHeaderClass sopaHeader = new ArchivesSvc.SoapHeaderClass();
                ArchivesSvc.ArchivesServiceSoapClient client = new Aliyeye.Car.Net.UI.ArchivesSvc.ArchivesServiceSoapClient();
                float rate = client.GetPointsRate(sopaHeader);

                decimal sum = (modelReserve.RentReceivable + modelReserve.OvertimeAmount + modelReserve.SuperDriverAmount) * Convert.ToDecimal(rate);

                points = Convert.ToInt64(Math.Round(sum, 0));
                modelReserve.Points = points;
                modelReserve.PointRate = rate;
            }

            ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
            proxy => proxy.FinishOrder(sopaHeaderReserveSvc, modelCar.Id, modelReserve.Id, Convert.ToInt64(txtCurrentKM.Text), modelReserve, InputBillingAmount),
            result =>
            {
                if (result.Error == null)
                {
                    PageCommon.Notify("还车结算成功！");
                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    txtCurrentKM.Enabled = false;
                    lblOtherAmount.Enabled = false;
                    txtMarks.Enabled = false;
                    btnSave.Enabled = false;
                    rdbIsCompletedCheckout.Enabled = false;
                    isSave = true;

                    btnSave.Enabled = false;
                }
                else
                {
                    PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                }
            },
            this
            );
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            if (!isSave)
            {
                if (PageCommon.Confirm("你还未结算，现在结算吗？"))
                {
                    SaveInfo();
                }
                else
                {
                    this.Close();
                }
            }
            else
            {
                this.Close();
            }
        }

        private void lblOtherAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            IsNumberMoney(txtCurrentKM, e);
        }

        private void lblOtherAmount_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(lblOtherAmount.Text))
            {
                PageCommon.Alert("餐费住宿费不能为空！");
                lblOtherAmount.Text = "0";
                GetTotalAmount();
                return;
            }
            else
            {
                GetTotalAmount();
            }
        }

        private void picbBills_Click(object sender, EventArgs e)
        {
            BillingDetailsList show = new BillingDetailsList(this.reserveID);
            show.ShowDialog();
        }

        private void lklblShowDetails_Click(object sender, EventArgs e)
        {
            BillingDetailsList show = new BillingDetailsList(this.reserveID);
            show.ShowDialog();
        }

        //打印单据
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (!isSave)
            {
                PageCommon.Alert("请先结算，在打印单据！");
                return;
            }

            DataSet ds = null;
            CompanySvc.SoapHeaderClass sopaHeaderCompany = new CompanySvc.SoapHeaderClass();
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            ServiceManipulator.SafeAsyncExecution<CompanySvc.CompanyServiceSoapClient>(
                    proxy => proxy.GetList(sopaHeaderCompany, ""),
                    result =>
                    {
                        if (result.Error == null)
                        {
                            ds = (DataSet)result.Result;
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                Model.Company model = new Model.Company();

                                model.ComName = ds.Tables[0].Rows[0]["ComName"].ToString();
                                model.ComAddr = ds.Tables[0].Rows[0]["ComAddr"].ToString();
                                model.Tel = ds.Tables[0].Rows[0]["Tel"].ToString();
                                model.UserName = ds.Tables[0].Rows[0]["UserName"].ToString();
                                model.Url = ds.Tables[0].Rows[0]["Url"].ToString();
                                model.Marks = ds.Tables[0].Rows[0]["Marks"].ToString();

                                //开始打印结算单
                                WordHelper wordHelp = new WordHelper();
                                if (wordHelp.PrintSettlement(model, customerInfo, modelReserve, modelCar, true, Convert.ToDecimal(lblTotalAmount.Text), Login.LogTrueName, 0))
                                {
                                    PageCommon.Notify("打印成功！");
                                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                                }
                                else
                                {
                                    PageCommon.Alert("打印失败！");
                                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                                }
                            }
                            else
                            {
                                PageCommon.Alert("打印失败！");
                                overlay.FadeOut(); Cursor.Current = Cursors.Default;
                            }
                        }
                        else
                        {
                            PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        }
                    },
                    this
                );
        }

        private void lblNowDate_Click(object sender, EventArgs e)
        {
            this.dtpReturnDate.Visible = true;
            dtpReturnDate.Value = Convert.ToDateTime(lblNowDate.Text);
        }

        private void dtpReturnDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                lblNowDate.Text = dtpReturnDate.Value.ToString("yyyy-MM-dd HH:mm:00");
                dtpReturnDate.Visible = false;

                DateTime dtReturn = Convert.ToDateTime(lblNowDate.Text);
                //超时计算
                Int64 timeout = Convert.ToInt64(dtReturn.Subtract(modelReserve.EndBooktime).TotalHours);
                if (timeout > 0)
                    lblTimeOut.Text = timeout.ToString();
                else
                    lblTimeOut.Text = "0";

                lblOvertimeAmount.Text = (Convert.ToDecimal(lblTimeoutPrie.Text) * Convert.ToDecimal(lblTimeOut.Text)).ToString();

                GetTotalAmount();
            }
        }

    }
}
